package validate

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gvalid"
	"regexp"
	"time"
)

// RuleRegisterCommon 注册公共规则
func RuleRegisterCommon() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`alpha-dash`:    RuleAlphaDash,
		`alpha-num`:     RuleAlphaNum,
		`chs-dash`:      RuleChsDash,
		`chs-alpha-num`: RuleChsAlphaNum,
		`is-hex`:        RuleIsHex,
		`sms-captcha`:   RuleSmsCaptcha,
		`dates`:         RuleDates,
	})
}

// RuleAlphaDash 匹配字母数字下划线和破折号
func RuleAlphaDash(ctx context.Context, in gvalid.RuleFuncInput) error {
	if len(in.Value.String()) == 0 {
		return nil
	}
	if !utils.AlphaDash(in.Value.String()) {
		if len(in.Message) == 0 {
			in.Message = `只允许字母和数字，下划线_及破折号-`
		}
		return gerror.New(in.Message)
	}
	return nil
}

// RuleAlphaNum 字母和数字
func RuleAlphaNum(ctx context.Context, in gvalid.RuleFuncInput) error {
	if len(in.Value.String()) == 0 {
		return nil
	}
	if !utils.AlphaNum(in.Value.String()) {
		if len(in.Message) == 0 {
			in.Message = `只允许字母和数字`
		}
		return gerror.New(in.Message)
	}
	return nil
}

// RuleChsDash  验证汉字、字母和数字，下划线_及破折号-
func RuleChsDash(ctx context.Context, in gvalid.RuleFuncInput) error {
	if len(in.Value.String()) == 0 {
		return nil
	}
	if !utils.ChsDash(in.Value.String()) {
		if len(in.Message) == 0 {
			in.Message = `只允许汉字、字母和数字，下划线_及破折号-`
		}
		return gerror.New(in.Message)
	}
	return nil
}

// RuleChsAlphaNum 匹配汉字、字母和数字
func RuleChsAlphaNum(ctx context.Context, in gvalid.RuleFuncInput) error {
	if len(in.Value.String()) == 0 {
		return nil
	}
	if !utils.ChsAlphaNum(in.Value.String()) {
		if len(in.Message) == 0 {
			in.Message = `只允许汉字、字母和数字`
		}
		return gerror.New(in.Message)
	}
	return nil
}

// RuleIsHex 匹配十六进制
func RuleIsHex(ctx context.Context, in gvalid.RuleFuncInput) error {
	if !utils.IsHex(in.Value.String()) {
		return gerror.New(in.Message)
	}
	return nil
}

// RuleSmsCaptcha 短信验证码
func RuleSmsCaptcha(ctx context.Context, in gvalid.RuleFuncInput) error {
	if !regexp.MustCompile(`^[\d]{6}$`).MatchString(in.Value.String()) {
		return gerror.New(in.Message)
	}
	return nil
}

// RuleDates 验证时间格式组
func RuleDates(ctx context.Context, in gvalid.RuleFuncInput) error {
	if len(in.Value.Strings()) == 0 {
		return nil
	}
	// 解析时间格式
	for _, date := range in.Value.Strings() {
		_, err := time.Parse(time.DateTime, date)
		if err != nil {
			return exception.Newf(`[%s]时间格式错误`, date)
		}
	}
	return nil
}
